import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:shenfuhui/config/config.dart';

import '../utils/singleton_manager.dart';

typedef PageChanged = void Function(int index);

class PhotoPreview extends StatefulWidget {
  final int defaultImage; //默认第几张
  final PageChanged? pageChanged; //切换图片回调

  const PhotoPreview({
    Key? key,
    this.defaultImage = 1,
    this.pageChanged,
  }) : super(key: key);

  @override
  State<PhotoPreview> createState() => _PhotoPreviewState();
}

class _PhotoPreviewState extends State<PhotoPreview> {
  List galleryItems = []; //图片列表
  late int tempSelect;

  @override
  void initState() {
    super.initState();
    galleryItems = SingletonManager.instance.galleryItems;
    tempSelect = widget.defaultImage + 1;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Config.colorBg,
      body: Stack(
        children: [
          PhotoViewGallery.builder(
              scrollPhysics: const BouncingScrollPhysics(),
              builder: (BuildContext context, int index) {
                return PhotoViewGalleryPageOptions(
                  imageProvider: NetworkImage(galleryItems[index]),
                );
              },
              scrollDirection: Axis.horizontal,
              itemCount: galleryItems.length,
              backgroundDecoration: const BoxDecoration(color: Config.colorBg),
              pageController: PageController(initialPage: widget.defaultImage),
              onPageChanged: (index) => setState(() {
                    tempSelect = index + 1;
                    if (widget.pageChanged != null) {
                      widget.pageChanged!(index);
                    }
                  })),
          Positioned(
            ///布局自己换
            right: 20,
            bottom: 20,
            child: Text(
              '$tempSelect/${galleryItems.length}',
              style: const TextStyle(color: Colors.white),
            ),
          )
        ],
      ),
    );
  }
}
